package com.parttimetask.activities;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.parttimetask.R;
import com.parttimetask.bean.ExcelBean;
import com.parttimetask.databinding.ActivityAdminBinding;
import com.parttimetask.utils.ContentUriUtil;
import com.parttimetask.utils.ExcelUtil;
import com.parttimetask.utils.Http;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AdminActivity extends AppCompatActivity {
    private static final int PICK_PBpower = 2;
    private static final int PICK_Solar = 3;
    private static final int PB_POWER_RESULT = 4;
    private static final int SOLAR_POWER_RESULT = 5;
    private ActivityAdminBinding binding;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityAdminBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setTitle("Admin");
        binding.adminIconPopower.setOnClickListener(view -> startActivityForResult(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI),PICK_PBpower));
        binding.adminIconSolar.setOnClickListener(view -> startActivityForResult(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI),PICK_Solar));binding.adminSqlUrl.setOnClickListener(view -> startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Http.BASE_URL+"admin/"))));
        Glide.with(this).setDefaultRequestOptions(new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)).load(Http.BASE_URL+"files/jobIcon/PBpower.png").into(binding.adminIconPopower);
        Glide.with(this).setDefaultRequestOptions(new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)).load(Http.BASE_URL+"files/jobIcon/Solar.png").into(binding.adminIconSolar);
        Http.get("configure/getConfigure/", new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) { e.printStackTrace(); }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                runOnUiThread(() -> {
                    try {
                        JSONObject bo = new JSONObject(response.body().string());
                        binding.adminPbJobType.setText(bo.getJSONObject("pb").getString("joyType"));
                        binding.adminPbLink.setText(bo.getJSONObject("pb").getString("applyLink"));
                        binding.adminPbLookCount.setText(bo.getJSONObject("pb").getString("look"));
                        binding.adminPbPayType.setText(bo.getJSONObject("pb").getString("payType"));
                        binding.adminPbSalary.setText(bo.getJSONObject("pb").getString("salary"));
                        binding.adminSolarJobType.setText(bo.getJSONObject("solar").getString("joyType"));
                        binding.adminSolarLink.setText(bo.getJSONObject("solar").getString("applyLink"));
                        binding.adminSolarLook.setText(bo.getJSONObject("solar").getString("look"));
                        binding.adminSolarPayType.setText(bo.getJSONObject("solar").getString("payType"));
                        binding.adminSolarSalary.setText(bo.getJSONObject("solar").getString("salary"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (android.R.id.home==item.getItemId()){ finish(); }
        if (item.getItemId()==R.id.menu_save){
            try {
                JSONObject jo=new JSONObject();
                jo.put("pb",new JSONObject().put("salary", binding.adminPbSalary.getText().toString()).put("look",binding.adminPbLookCount.getText().toString()).put("payType",binding.adminPbPayType.getText().toString()).put("joyType",binding.adminPbJobType.getText().toString()).put("applyLink",binding.adminPbLink.getText().toString()));
                jo.put("solar",new JSONObject().put("salary", binding.adminSolarSalary.getText().toString()).put("look",binding.adminSolarLook.getText().toString()).put("payType",binding.adminSolarPayType.getText().toString()).put("joyType",binding.adminSolarJobType.getText().toString()).put("applyLink",binding.adminSolarLink.getText().toString()));
                Http.post(jo, "configure/update/", new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) {
                        runOnUiThread(() -> Toast.makeText(AdminActivity.this, "All msg saved", Toast.LENGTH_SHORT).show());
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (item.getItemId()==R.id.menu_export_contact){
            Http.get("contact/get/", new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    runOnUiThread(() -> {
                        try {
                            JSONArray ja = new JSONObject(response.body().string()).getJSONArray("data");
                            File file1 = new File(Environment.getExternalStorageDirectory().getPath() + "/partTimeTask/");
                            if (!file1.exists())file1.mkdirs();
                            File file = new File(file1, "mobile.xls");
                            List<ExcelBean> excelBeanList = new ArrayList<>();
                            for (int i = 0; i < ja.length(); i++) {
                                JSONObject jo = ja.getJSONObject(i);
                                ExcelBean excelBean = new ExcelBean(i+"",new String[]{jo.getString("name"),jo.getString("number")});
                                excelBeanList.add(excelBean);
                            }
                            ExcelUtil.initExcel(file.getAbsolutePath(), "手机号", new String[]{"序号","名字", "手机号"});
                            ExcelUtil.writeObjListToExcel(excelBeanList, file.getAbsolutePath(), AdminActivity.this);
                        } catch (Exception  e) {
                            e.printStackTrace();
                        }
                    });
                }
            });
        }
        if (item.getItemId()==R.id.menu_mobile){
            EditText et=new EditText(this);
            et.setHint("mobile area code");
            et.setText("86");
            AlertDialog.Builder dialog=new AlertDialog.Builder(this);
            dialog.setView(et).setPositiveButton("confirm", (dialogInterface, i) -> Http.get("mobileArea/?code="+et.getText().toString(), new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    runOnUiThread(() -> Toast.makeText(AdminActivity.this, "Ok", Toast.LENGTH_SHORT).show());
                }
            })).setNegativeButton("cancel",null).show();
        }
        if (item.getItemId()==R.id.menu_export_user){
            Http.get("user/queryAll/", new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    runOnUiThread(() -> {
                        try {
                            JSONArray ja = new JSONObject(response.body().string()).getJSONArray("data");
                            File file1 = new File(Environment.getExternalStorageDirectory().getPath() + "/partTimeTask/");
                            if (!file1.exists())file1.mkdirs();
                            File file = new File(file1, "users.xls");
                            List<ExcelBean> excelBeanList = new ArrayList<>();
                            for (int i = 0; i < ja.length(); i++) {
                                JSONObject jo = ja.getJSONObject(i);
                                ExcelBean excelBean = new ExcelBean(i+"",new String[]{
                                        jo.getString("name"),
                                        jo.getString("mobile"),
                                        jo.getString("email"),
                                        jo.getString("password"),
                                        jo.getString("gender"),
                                        jo.getString("age")
                                });
                                excelBeanList.add(excelBean);
                            }
                            ExcelUtil.initExcel(file.getAbsolutePath(), "手机号", new String[]{"序号","名字", "手机号","邮箱","密码","性别","年龄"});
                            ExcelUtil.writeObjListToExcel(excelBeanList, file.getAbsolutePath(), AdminActivity.this);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                }
            });
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_admin, menu);
        return true;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==PICK_PBpower&&resultCode==-1){
            String path= ContentUriUtil.getPath(this, data.getData());
            startActivityForResult(new Intent(this,CropImgActivity.class).putExtra("path", path).putExtra("filename","cache_pb.jpg"),PB_POWER_RESULT);
        }
        if (requestCode==PB_POWER_RESULT){
            File file=new File(getExternalCacheDir(), "/cache_pb.jpg");
            binding.adminIconPopower.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
            Http.upload("configure/uploadImg/?type=PBpower", file, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                }
            });
        }
        if (requestCode==PICK_Solar&&resultCode==-1){
            String path= ContentUriUtil.getPath(this, data.getData());
            startActivityForResult(new Intent(this,CropImgActivity.class).putExtra("path", path).putExtra("filename","cache_solar.jpg"),SOLAR_POWER_RESULT);
        }
        if (requestCode==SOLAR_POWER_RESULT){
            File file=new File(getExternalCacheDir(), "/cache_solar.jpg");
            binding.adminIconSolar.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
            Http.upload("configure/uploadImg/?type=Solar", file, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                }
            });

        }
    }
}
